package dbimpl

import (
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"multimedia/utils"
	"strconv"
	"strings"
	"time"

	_ "github.com/go-sql-driver/mysql"
	log "github.com/sirupsen/logrus"
)

// MysqlImpl ...
type MysqlImpl struct {
	dblink *sql.DB
}

func NewMysql(linkstr string) *MysqlImpl {
	db, err := sql.Open("mysql", linkstr)
	if err != nil {
		log.WithField("func:", "NewMysql").Warnf("connect mysql error:%v [%v]", linkstr, err)
		return nil
	}
	db.SetMaxOpenConns(1024)
	db.SetMaxIdleConns(0)
	err = db.Ping()
	if err != nil {
		log.WithField("func:", "NewMysql").Warnf("connect mysql error:%v [%v],%v", linkstr, err, db.Stats())
		return nil
	}
	log.WithField("func:", "NewMysql").Infof("init mysql the link is:%v successful", linkstr)
	return &MysqlImpl{dblink: db}
}
func (m *MysqlImpl) Close() {
	m.dblink.Close()
}

// 根据主键获取会议信息
func (m *MysqlImpl) GetConferById(confeId int64) *utils.ConferenceRes {
	defer utils.HandlePanic()
	var confInfo utils.ConferenceRes
	QueryStr := "select id, room_id,`type`,theme, creator, date_format(start_time,'%Y-%m-%d %T'), date_format(end_time,'%Y-%m-%d %T') from mc_conference where id = ?"
	rows, err := m.dblink.Query(QueryStr, confeId)
	if err != nil {
		log.WithField("Func", "GetConferById").Warnf("Query:[%v] err:%v", QueryStr, err)
		return nil
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&confInfo.Id, &confInfo.RoomId, &confInfo.Type, &confInfo.Theme, &confInfo.Creator,
			&confInfo.StartTime, &confInfo.EndTime)
		if err != nil {
			log.WithField("Func", "GetConferenceById").Warnf("scan:[%v] err:%v", QueryStr, err)
			return nil
		}
	} else {
		return nil
	}
	return &confInfo
}

func (m *MysqlImpl) GetConfeByRoomId(roomId string) *utils.Confer {
	defer utils.HandlePanic()
	confer := &utils.Confer{}
	sql := "select id, room_id, theme, date_format(start_time, '%Y-%m-%d %T'), creator, record_flag from mc_conference where room_id=? order by created_at desc limit 1"
	rows, err := m.dblink.Query(sql, roomId)
	if err != nil {
		log.WithField("Func", "GetConfeByRoomId").Errorf("Query:[%v] error:%v", sql, err)
		return nil
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&confer.Id, &confer.RoomId, &confer.Theme, &confer.StartTime, &confer.Creator, &confer.RecordCount)
		if err != nil {
			log.WithField("Func", "GetConfeByRoomId").Errorf("scan:[%v] error:%v", sql, err)
			return nil
		}
	}
	return confer
}

// 获取指定时间内将要开始的会议
func (m *MysqlImpl) GetNotifyConferList(interval int) *[]utils.ConfeNotice {
	defer utils.HandlePanic()
	sql := "select c.id, room_id, theme, creator, date_format(start_time, '%Y-%m-%d %T'), eau.nickname, " +
		"date_format(end_time, '%Y-%m-%d %T') from mc_conference c left join emedia_app_user eau on eau.id = c.creator " +
		"where c.type=1 and TIMESTAMPDIFF(second,now(),start_time) >= 0 and TIMESTAMPDIFF(second,now(),start_time) < ?;"
	rows, err := m.dblink.Query(sql, interval)
	if err != nil {
		log.WithField("Func", "GetNotifyConferList").Warnf("Query:[%v] err:%v", sql, err)
		return nil
	}
	defer rows.Close()
	var confeList = make([]utils.ConfeNotice, 0)
	for rows.Next() {
		var confe utils.ConfeNotice
		err = rows.Scan(&confe.Id, &confe.RoomId, &confe.Theme, &confe.CreatorId, &confe.StartTime,
			&confe.Creator, &confe.EndTime)
		if err != nil {
			log.WithField("Func", "GetNotifyConferList").Warnf("scan:[%v] err:%v", sql, err)
			continue
		}
		confeList = append(confeList, confe)
	}
	return &confeList
}

func (m *MysqlImpl) NewGetRoomInfoByRoomId(roomId string) *utils.RoomInfo {
	defer utils.HandlePanic()
	var roomInfo utils.RoomInfo
	QueryStr := "select id, conf_id, password from emedia_room_info where room_id = ?"
	rows, err := m.dblink.Query(QueryStr, roomId)
	if err != nil {
		log.WithField("Func", "GetRoomInfoByRoomId").Warnf("Query:[%v] error:%v", QueryStr, err)
		return nil
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&roomInfo.Id, &roomInfo.ConfId, &roomInfo.Password)
		if err != nil {
			log.WithField("Func", "GetRoomInfoByRoomId").Warnf("scan:[%v] error:%v", QueryStr, err)
			return nil
		}
	}
	return &roomInfo
}

// 根据房间号获取会议信息
func (m *MysqlImpl) GetRoomInfoByRoomId(roomId string) *utils.RoomInfo {
	defer utils.HandlePanic()
	var roomInfo utils.RoomInfo
	QueryStr := "select id, conf_id, password from emedia_room_info where room_id = ? and state <> 2 and state <> 3"
	rows, err := m.dblink.Query(QueryStr, roomId)
	if err != nil {
		log.WithField("Func", "GetRoomInfoByRoomId").Warnf("Query:[%v] error:%v", QueryStr, err)
		return nil
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&roomInfo.Id, &roomInfo.ConfId, &roomInfo.Password)
		if err != nil {
			log.WithField("Func", "GetRoomInfoByRoomId").Warnf("scan:[%v] error:%v", QueryStr, err)
			return nil
		}
	}
	return &roomInfo
}
func (m *MysqlImpl) UpdateWhiteBoardFlag(conferid int64, whiteboardflag int) {
	defer utils.HandlePanic()
	sql := "update mc_conference set WhiteBoardFlag=? where id=?"
	_, err := m.dblink.Exec(sql, whiteboardflag, conferid)
	if err != nil {
		log.WithField("Func", "UpdateWhiteBoardFlag").Errorf("update mc_conference set confer:%d whiteboardflag:%d err:%v", conferid, whiteboardflag, err)
	} else {
		log.WithField("Func", "UpdateWhiteBoardFlag").Infof("update mc_conference set confer:%d whiteboardflag:%d", conferid, whiteboardflag)
	}
}
func (m *MysqlImpl) CloseRoomByRoomId(roomid string, ordinal int, timestamp int64) {
	defer utils.HandlePanic()
	sql := "update emedia_room_info set state=?, conf_close_time=? where room_id=? and state <> 2 and state <> 3"
	_, err := m.dblink.Exec(sql, ordinal, timestamp, roomid)
	log.WithField("Func", "CloseRoomByRoomId").Errorf("update emedia_room_info err %v,%s,%d", err, roomid, ordinal)

	if err != nil {
		log.WithField("Func", "CloseRoomByRoomId").Errorf("update emedia_room_info err %v,%s,%d", err, roomid, ordinal)
	}
}
func (m *MysqlImpl) CheckRoomState(roomId string) *utils.RoomState {
	defer utils.HandlePanic()
	roomState := utils.RoomState{
		ConfeId: 0,
	}
	zeroTime := utils.GetZeroTime(time.Now())
	sql := "select id, type, theme, creator, allow from mc_conference where room_id=? and end_time > ?"
	rows, err := m.dblink.Query(sql, roomId, zeroTime)
	if err != nil {
		log.WithField("Func", "CheckRoomState").Errorf("Query:[%v] error:%v", sql, err)
		return nil
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&roomState.ConfeId, &roomState.Type, &roomState.Theme, &roomState.Creator, &roomState.Allow)
		if err != nil {
			log.WithField("Func", "CheckRoomState").Errorf("scan:[%v] error:%v", sql, err)
			return nil
		}
	}
	if roomState.ConfeId == 0 {
		return &roomState
	}
	return &roomState
}

// 根据房间号查询预定会议和当前会议
func (m *MysqlImpl) GetRoomState(roomId string) *utils.RoomState {
	defer utils.HandlePanic()
	var roomState utils.RoomState
	zeroTime := utils.GetZeroTime(time.Now())
	QueryStr := "select c.id, c.type, c.theme, c.creator,c.moderator, c.allow,c.disable_audio,c.setPassword,c.meetingPassword,c.WhiteBoardFlag, ifnull(ri.state, 0) state, eau.nickname from mc_conference c " +
		"left join emedia_room_info ri on c.room_id = ri.room_id and ri.state <> 3 " +
		"left join emedia_app_user eau on eau.id = c.creator " +
		"where c.version <> -1 and c.room_id = ? and c.end_time > ?"
	rows, err := m.dblink.Query(QueryStr, roomId, zeroTime)
	if err != nil {
		log.WithField("Func", "GetRoomState").Errorf("Query:[%v] error:%v", QueryStr, err)
		return nil
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&roomState.ConfeId, &roomState.Type, &roomState.Theme, &roomState.Creator, &roomState.Moderator, &roomState.Allow,
			&roomState.DisableAudio, &roomState.SetPassword, &roomState.MeetingPassword, &roomState.WhiteBoardFlg, &roomState.State, &roomState.Host)
		if err != nil {
			log.WithField("Func", "GetRoomState").Errorf("scan:[%v] error:%v", QueryStr, err)
			return nil
		}
	}
	return &roomState
}

// 添加会议信息
func (m *MysqlImpl) AddConference(Confer *utils.AddConferReq, roomId string) int64 {
	defer utils.HandlePanic()
	now := utils.GetCurrentTime()
	closeDate := sql.NullString{String: "", Valid: false}
	if Confer.CloseDate != "" {
		closeDate = sql.NullString{String: Confer.CloseDate, Valid: true}
	}
	log.WithField("Func", "AddConference").Warnf(" the confer is:%v", Confer)

	sql := "INSERT INTO mc_conference values (null,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
	r, err := m.dblink.Exec(sql, roomId, 0, Confer.Type, Confer.Theme, Confer.StartTime, Confer.EndTime,
		Confer.TimeZone, Confer.Creator, Confer.Toplimit, Confer.Allow, Confer.Cycle, closeDate, now, now, 0,
		false, Confer.DisableAudio, Confer.Watermark, 0, Confer.SetPassword, Confer.MeetingPassword, 0)
	if err != nil {
		log.WithField("Func", "AddConference").Warnf("sql:[%v] %v", sql, err)
		return 0
	}
	no, _ := r.RowsAffected()
	if no < 1 {
		return no
	}
	count, _ := r.LastInsertId()
	return count
}

// 添加周期性会议
func (m *MysqlImpl) CycleConfeInsert(sql string) int64 {
	defer utils.HandlePanic()
	result, err := m.dblink.Exec(sql)
	if err != nil {
		log.WithField("Func", "CycleConfeInsert").Errorf("insert DB fail. sql:%s. %v", sql, err)
		return 0
	}
	no, _ := result.RowsAffected()
	return no
}

// 创建当前会议信息
func (m *MysqlImpl) CreateRoomInfo(Confer *utils.RoomInfoCreate) int64 {
	defer utils.HandlePanic()
	Id := utils.IdGenerate()
	currentTime := utils.GetCurrentTime()
	InsertSql := "INSERT INTO emedia_room_info values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
	_, err := m.dblink.Exec(InsertSql, Id, Confer.Uuid, Confer.AppId, Confer.Creator, Confer.RoomId, Confer.RoomType,
		0, Confer.ConfrId, Confer.Password, nil, nil, nil, currentTime, currentTime, 0, Confer.ConfrType)
	if err != nil {
		log.WithField("Func", "GetConfListByParam").Errorf("querySql:[%v] err: %v", InsertSql, err)

	}
	return Id
}

// 会议列表
func (m *MysqlImpl) GetConfListByParam(userId int64, confeListRes *[]utils.ConfeRes) {
	defer utils.HandlePanic()
	curTime := utils.GetZeroTime(time.Now())
	querySql := "select c.id, c.group_id, room_id, `type`, theme, date_format(start_time, '%Y-%m-%d') date, date_format(start_time, '%Y-%m-%d %T'), " +
		"date_format(end_time, '%Y-%m-%d %T'), cycle, allow, eau.nickname,c.disable_audio,c.watermark,c.setPassword,c.meetingPassword from mc_conference c left join emedia_app_user eau on c.creator = eau.id " +
		"where Creator = ? and end_time > ? and type = 1 and c.version <> -1 order by start_time desc, date desc "
	rows, err := m.dblink.Query(querySql, userId, curTime)
	if err != nil {
		log.WithField("Func", "GetConfListByParam").Warnf("querySql:[%v] err: %v", querySql, err)
		return
	}
	defer rows.Close()
	groupMap := make(map[string]bool, 0)
	date := ""
	datemp := make(map[string]int, 0)
	for rows.Next() {
		var confer utils.ConferenceRes
		err = rows.Scan(&confer.Id, &confer.GroupId, &confer.RoomId, &confer.Type, &confer.Theme, &date,
			&confer.StartTime, &confer.EndTime, &confer.Cycle, &confer.Allow, &confer.Creator,
			&confer.DisableAudio, &confer.Watermark, &confer.SetPassword, &confer.MeetingPassword)
		if err != nil {
			log.WithField("Func", "GetConfListByParam").Warnf("scan error!sql:[%s]", querySql, err)
			continue
		}
		// 周期会议只取日期最近一条数据
		groupId := confer.GroupId
		if confer.Cycle == 1 {
			if _, ok := groupMap[groupId]; ok {
				continue
			} else {
				groupMap[groupId] = true
			}
		}
		// 组织返回数据
		if v, ok := datemp[date]; ok {
			(*confeListRes)[v].ConfeList = append((*confeListRes)[v].ConfeList, confer)
		} else {
			datemp[date] = len(*confeListRes)
			clr := utils.ConfeRes{
				Date:      date,
				ConfeList: make([]utils.ConferenceRes, 0),
			}
			clr.ConfeList = append(clr.ConfeList, confer)
			*confeListRes = append(*confeListRes, clr)
		}
	}
}

// 周期会议列表
func (m *MysqlImpl) GetCycleConfList(groupId string, confeListRes *[]utils.ConfeRes) {
	defer utils.HandlePanic()
	curTime := utils.GetZeroTime(time.Now())
	querySql := "select c.id, c.group_id, room_id, `type`, theme, date_format(start_time, '%Y-%m') date, date_format(start_time, '%Y-%m-%d %T'), " +
		"date_format(end_time, '%Y-%m-%d %T'), cycle, eau.nickname,c.disable_audio,c.watermark,c.setPassword,c.meetingPassword " +
		"from mc_conference c left join emedia_app_user eau on c.creator = eau.id " +
		"where end_time > ? and group_id = ? and c.version <> -1 order by start_time, date"
	rows, err := m.dblink.Query(querySql, curTime, groupId)
	if err != nil {
		log.WithField("Func", "GetCycleConfList").Warnf("querySql:[%v] err: %v", querySql, err)
		return
	}
	defer rows.Close()
	date := ""
	datemp := make(map[string]int, 0)
	for rows.Next() {
		var confer utils.ConferenceRes
		err = rows.Scan(&confer.Id, &confer.GroupId, &confer.RoomId, &confer.Type, &confer.Theme, &date,
			&confer.StartTime, &confer.EndTime, &confer.Cycle, &confer.Creator, &confer.DisableAudio, &confer.Watermark,
			&confer.SetPassword, &confer.MeetingPassword)
		if err != nil {
			log.WithField("Func", "GetCycleConfList").Warnf("scan error!sql:[%s]", querySql, err)
			continue
		}
		// 组织返回数据
		if v, ok := datemp[date]; ok {
			(*confeListRes)[v].ConfeList = append((*confeListRes)[v].ConfeList, confer)
		} else {
			datemp[date] = len(*confeListRes)
			clr := utils.ConfeRes{
				Date:      date,
				ConfeList: make([]utils.ConferenceRes, 0),
			}
			clr.ConfeList = append(clr.ConfeList, confer)
			*confeListRes = append(*confeListRes, clr)
		}
	}
}

// 查询会议人员关系
func (m *MysqlImpl) SelectRoomPlayer(roomId string, userId int64) int64 {
	defer utils.HandlePanic()
	var roomPlayersId int64
	sql := "select rp.id from emedia_room_info ri, emedia_room_players rp " +
		"where ri.id = rp.room_id and ri.room_id = ? and rp.player_name = ? and ri.state <> 2 and state <> 3;"
	rows, err := m.dblink.Query(sql, roomId, userId)
	if err != nil {
		log.WithField("Func", "GetRoomPlayer").Errorf("sql:[%s], %v", sql, err)
		return -1
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&roomPlayersId)
		if err != nil {
			log.WithField("Func", "GetRoomPlayer").Errorf("scan fail! sql:[%s], %v", sql, err)
			return -1
		}
	}
	return roomPlayersId
}

// 编辑会议
func (m *MysqlImpl) EditConferenceInfo(Confer *utils.ConfeUpdate) bool {
	defer utils.HandlePanic()
	closeDate := sql.NullString{String: "", Valid: false}
	if Confer.CloseDate != "" {
		closeDate = sql.NullString{String: Confer.CloseDate, Valid: true}
	}
	updateTime := utils.GetCurrentTime()
	EditSql := "update mc_conference set group_id = ?, theme = ?, start_time = ?, end_time = ?," +
		"allow = ?, cycle = ?, cycle_close_time = ?, updated_at = ?,disable_audio=?,watermark=?,setPassword=?,meetingPassword=? where id = ?"
	res, err := m.dblink.Exec(EditSql, Confer.GroupId, Confer.Theme, Confer.StartTime, Confer.EndTime,
		Confer.Allow, Confer.Cycle, closeDate, updateTime, Confer.DisableAudio, Confer.Watermark, Confer.SetPassword, Confer.MeetingPassword, Confer.Id)
	if err != nil {
		log.WithField("Func", "EditConferenceInfo").Warnf("editSql:[%v], error:%v", EditSql, err)
		return false
	}
	var flag = true
	num, _ := res.RowsAffected()
	if num < 1 {
		flag = false
	}
	return flag
}

// 修改会议主持人
func (m *MysqlImpl) EditConferModerator(moderatorId int64, roomId int64) bool {
	defer utils.HandlePanic()
	updateTime := utils.GetCurrentTime()
	editSql := "update mc_conference set moderator = ?, updated_at = ? where id = ?"
	ret, err := m.dblink.Exec(editSql, moderatorId, updateTime, roomId)
	if err != nil {
		log.WithField("Func", "EditConferModerator").Warnf("editSql:[%v], error:%v", editSql, err)
		return false
	}
	var flag = true
	num, _ := ret.RowsAffected()
	if num < 1 {
		flag = false
	}
	return flag
}

// 修改会议状态
func (m *MysqlImpl) EditConferState(state int8, id int64) (bool, error) {
	defer utils.HandlePanic()
	updateTime := utils.GetCurrentTime()
	editSql := "update emedia_room_info set state = ?, updated_at = ? where id = ?"
	ret, err := m.dblink.Exec(editSql, state, updateTime, id)
	if err != nil {
		log.WithField("Func", "EditConferState").Warnf("editSql:[%v], error:%v", editSql, err)
		return false, err
	}
	var flag = true
	num, _ := ret.RowsAffected()
	if num < 1 {
		flag = false
	}
	return flag, nil
}

// 删除会议
func (m *MysqlImpl) DeleteConferenceInfo(id int64) int64 {
	defer utils.HandlePanic()
	updateTime := utils.GetCurrentTime()
	delSql := "update mc_conference set version = -1, updated_at = ? where id = ?"
	res, err := m.dblink.Exec(delSql, updateTime, id)
	if err != nil {
		log.WithField("Func", "DeleteConferenceInfo").Warnf("delSql:[%v] error: %v", delSql, err)
		return -1
	}
	num, _ := res.RowsAffected()
	return num
}

// 删除周期会议
func (m *MysqlImpl) DeleteCycleConfe(groupId string) int64 {
	defer utils.HandlePanic()
	delSql := `delete from mc_conference where group_id = ? and room_id not in (select * from 
	(select distinct(ri.room_id) from mc_conference c,emedia_room_info ri where c.room_id = ri.room_id and c.group_id = ?)tmp);`

	res, err := m.dblink.Exec(delSql, groupId, groupId)
	if err != nil {
		log.WithField("Func", "DeleteCycleConfe").Warnf("delSql:[%v] error: %v", delSql, err)
		return -1
	}
	num, _ := res.RowsAffected()
	return num
}

// 更新周期会议删除状态
func (m *MysqlImpl) DeleteCloseCycleConfe(groupId string) int64 {
	defer utils.HandlePanic()
	updateTime := utils.GetCurrentTime()
	delSql := "update mc_conference set version = -1, updated_at = ? where group_id = ?"
	ret, err := m.dblink.Exec(delSql, updateTime, groupId)
	if err != nil {
		log.WithField("Func", "DeleteConferenceInfo").Warnf("delSql:[%v] error: %v", delSql, err)
		return -1
	}
	num, _ := ret.RowsAffected()
	return num
}

// 批量删除个人参会记录
func (m *MysqlImpl) BatchDeleteIndivRecord(ids string) bool {
	defer utils.HandlePanic()
	delSql := fmt.Sprintf("update emedia_room_players set version = -1 where id in (%s)", ids)
	ret, err := m.dblink.Exec(delSql)
	if err != nil {
		log.WithField("Func", "BatchDeleteIndivRecord").Warnf("delSql:[%v] error: %v", delSql, err)
		return false
	}
	var flag = true
	num, _ := ret.RowsAffected()
	if num < 1 {
		flag = false
	}
	return flag
}

// 添加周期会议规则
func (m *MysqlImpl) AddCycleRule(Confe *utils.AddConferReq, groupId string) int64 {
	defer utils.HandlePanic()
	currentTime := utils.GetCurrentTime()
	closeDate := sql.NullString{String: "", Valid: false}
	if Confe.CloseDate != "" {
		closeDate = sql.NullString{String: Confe.CloseDate, Valid: true}
	}
	sql := "INSERT INTO mc_cycle_rule values (null,?,?,?,?,?,?,?,?,?,?,?,?,?)"
	r, err := m.dblink.Exec(sql, groupId, Confe.CycleType, Confe.UntilType, closeDate, Confe.UntilCount, 0,
		Confe.CustomizedCycleType, Confe.CustomizedCycleStep, Confe.WeekOrder, "", currentTime, currentTime, 0)
	if err != nil {
		log.WithField("Func", "AddCycleRule").Errorf("sql:[%v] %v", sql, err)
		return 0
	}
	no, _ := r.RowsAffected()
	return no
}

// 根据groupId查询周期会议规则
func (m *MysqlImpl) GetCycleRuleByGroupId(groupId string) *utils.CycleRule {
	defer utils.HandlePanic()
	var cycleRule utils.CycleRule
	sql := `select id, group_id, cycle_type, until_type, until_date, until_count, customized_cycle_type,
	customized_cycle_step, week_order from mc_cycle_rule where group_id=?`
	rows, err := m.dblink.Query(sql, groupId)
	if err != nil {
		log.WithField("Func", "GetCycleRuleByGroupId").Errorf("Query:[%v] err:%v", sql, err)
		return nil
	}
	defer rows.Close()
	if rows.Next() {
		err := rows.Scan(&cycleRule.Id, &cycleRule.GroupId, &cycleRule.CycleType, &cycleRule.UntilType, &cycleRule.UntilDate,
			&cycleRule.UntilCount, &cycleRule.CustomizedCycleType, &cycleRule.CustomizedCycleStep, &cycleRule.WeekOrder)
		if err != nil {
			log.WithField("Func", "GetCycleRuleByGroupId").Errorf("scan:[%v] err:%v", sql, err)
			return nil
		}
	}
	return &cycleRule
}

// 修改周期会议规则
func (m *MysqlImpl) UpdateCycleRule(Confe *utils.ConfeUpdate) int64 {
	defer utils.HandlePanic()
	now := utils.GetCurrentTime()
	sql := `update mc_cycle_rule set cycle_type=?, until_type=?, until_date=?, until_count=?, customized_cycle_type=?,
	customized_cycle_step=?, week_order=?, updated_at=? where id=?`
	res, err := m.dblink.Exec(sql, Confe.CycleType, Confe.UntilType, Confe.CloseDate, Confe.UntilCount,
		Confe.CustomizedCycleType, Confe.CustomizedCycleStep, Confe.WeekOrder, now, Confe.Id)
	if err != nil {
		log.WithField("Func", "UpdateCycleRule").Errorf("editSql:[%v], error:%v", sql, err)
		return 0
	}
	num, _ := res.RowsAffected()
	return num
}

// 根据主键获取单个用户信息
func (m *MysqlImpl) GetUserInfo(id int64) (*utils.UserRes, error) {
	defer utils.HandlePanic()
	var user utils.UserRes
	querySql := "select id, username, nickname, phone_no, avatar from emedia_app_user where id = ?"
	rows, err := m.dblink.Query(querySql, id)
	if err != nil {
		log.WithField("Func", "GetUserInfo").Errorf("Query:[%v] err:%v", querySql, err)
		return nil, err
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&user.Id, &user.Username, &user.Nickname, &user.PhoneNo, &user.Avatar)
		if err != nil {
			log.WithField("Func", "GetUserInfo").Errorf("scan:[%v] err:%v", querySql, err)
			return nil, err
		}
	} else {
		return nil, errors.New("no data")
	}
	return &user, nil
}

// 根据手机号查询用户信息
func (m *MysqlImpl) GetUserInfoByPhone(phoneNo string) *utils.UserRes {
	defer utils.HandlePanic()
	var user utils.UserRes
	querySql := "select id, username, nickname, phone_no, password, avatar,avatar_circular from emedia_app_user where phone_no = ?"
	rows, err := m.dblink.Query(querySql, phoneNo)
	if err != nil {
		log.WithField("Func", "GetUserInfoByPhone").Warnf("Query:[%v] error:%v", querySql, err)
		return nil
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&user.Id, &user.Username, &user.Nickname, &user.PhoneNo, &user.Password, &user.Avatar, &user.AvatarCircular)
		if err != nil {
			log.WithField("Func", "GetUserInfoByPhone").Warnf("scan:[%v] error:%v", querySql, err)
			return nil
		}
	}
	return &user
}

// 添加用户信息
func (m *MysqlImpl) InsertUserInfo(user *utils.AppUser) int64 {
	defer utils.HandlePanic()
	Id := utils.IdGenerate()
	localDate := utils.GetCurrentTime()
	InsertSql := "INSERT INTO emedia_app_user values (?,?,?,?,?,?,?,?,?,?,?,?,?)"
	rows, err := m.dblink.Exec(InsertSql, Id, user.Uuid, user.AppId, user.Username, user.Nickname, user.PhoneNo,
		user.Password, user.Roles, user.Avatar, user.AvatarCircular, localDate, localDate, 0)
	if err != nil {
		log.WithField("Func", "InsertUserInfo").Warnf("InsertUserInfo the sql:[%v], error:%v", InsertSql, err)
		return 0
	}
	no, _ := rows.RowsAffected()
	if no < 1 {
		return 0
	}
	return Id
}

// 修改用户昵称
func (m *MysqlImpl) UpdateUserNickname(nickname string, userId int64) int {
	defer utils.HandlePanic()
	var flag int = 1
	localDate := utils.GetCurrentTime()
	sql := "update emedia_app_user set nickname=?, updated_at=? where id=?"
	ret, err := m.dblink.Exec(sql, nickname, localDate, userId)
	if err != nil {
		log.WithField("Func", "UpdateUserNickname").Warnf("UpdateUserNickname the sql:[%v], error:%v", sql, err)
		return 0
	}
	num, _ := ret.RowsAffected()
	if num < 1 {
		log.WithField("Func", "UpdateUserNickname").Warnf("modify nickname fail. rows affected: %v", num)
		flag = 0
	}
	return flag
}

// 修改密码
func (m *MysqlImpl) UpdateUserPasswd(password string, phone string) int {
	defer utils.HandlePanic()
	var flag int = 1
	localDate := utils.GetCurrentTime()
	sql := "update emedia_app_user set password=?, updated_at=? where phone_no=?"
	ret, err := m.dblink.Exec(sql, password, localDate, phone)
	if err != nil {
		log.WithField("Func", "UpdateUserNickname").Warnf("UpdateUserNickname the sql:[%v], error:%v", sql, err)
		return 0
	}
	num, _ := ret.RowsAffected()
	if num < 1 {
		log.WithField("Func", "UpdateUserNickname").Warnf("modify nickname fail. rows affected: %v", num)
		flag = 0
	}
	return flag
}

// 修改用户头像地址
func (m *MysqlImpl) UpdateUserAvatar(avatar string, userId int64) (bool, error) {
	defer utils.HandlePanic()
	localDate := utils.GetCurrentTime()
	sql := "update emedia_app_user set avatar=?, updated_at=? where id=?"
	ret, err := m.dblink.Exec(sql, avatar, localDate, userId)
	if err != nil {
		log.WithField("Func", "UpdateUserAvatar").Warnf("UpdateUserAvatar the sql:[%v], error:%v", sql, err)
		return false, err
	}
	var flag = true
	num, _ := ret.RowsAffected()
	if num < 1 {
		flag = false
	}
	return flag, nil
}

// 修改用户头像地址圆形头像
func (m *MysqlImpl) UpdateUserAvatarCircular(avatar string, userId int64) (bool, error) {
	defer utils.HandlePanic()
	localDate := utils.GetCurrentTime()
	sql := "update emedia_app_user set avatar_circular=?, updated_at=? where id=?"
	ret, err := m.dblink.Exec(sql, avatar, localDate, userId)
	if err != nil {
		log.WithField("Func", "UpdateUserAvatarCircular").Warnf("UpdateUserAvatarCircular the sql:[%v], error:%v", sql, err)
		return false, err
	}
	var flag = true
	num, _ := ret.RowsAffected()
	if num < 1 {
		flag = false
	}
	return flag, nil
}

// 新增消息信息
func (m *MysqlImpl) AddTidingsInfo(Tiding *utils.TidingsPO) int64 {
	defer utils.HandlePanic()
	InsertSql := "INSERT INTO mc_tidings values (null,?,?,?,?,?,?,?,?,?)"
	curTime := utils.GetCurrentTime()
	res, err := m.dblink.Exec(InsertSql, Tiding.Title, Tiding.Type, Tiding.BizId, Tiding.UserId, Tiding.Content,
		0, curTime, curTime, 0)
	if err != nil {
		log.WithField("Func", "AddTidingsInfo").Warnf("InsertSql:[%v] err: %v", InsertSql, err)
		return -1
	}
	num, _ := res.RowsAffected()
	return num
}

// 获取单条消息
func (m *MysqlImpl) GetTidingsInfo(id int) (*utils.TidingsVo, error) {
	defer utils.HandlePanic()
	var tidingVo utils.TidingsVo
	QueryStr := "select t.id, t.title, t.biz_id, t.content from mc_tidings t where id = ?"
	rows, err := m.dblink.Query(QueryStr, id)
	if err != nil {
		log.WithField("Func", "GetTidingsInfo").Warnf("QueryStr:[%v] error:%v", QueryStr, err)
		return nil, err
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&tidingVo.Id, &tidingVo.Title, &tidingVo.BizId, &tidingVo.Content)
		if err != nil {
			log.WithField("Func", "GetTidingsInfo").Warnf("scan:[%v] error:%v", QueryStr, err)
			return nil, err
		}
	}
	return &tidingVo, nil
}

// 消息列表
func (m *MysqlImpl) GetTidingsList(userId int) (*[]utils.TidingsVo, error) {
	defer utils.HandlePanic()
	QueryStr := `select t.id, t.title, t.biz_id, t.content, t.view, c.theme, date_format(c.start_time, '%Y-%m-%d %T') 
	from mc_tidings t left join mc_conference c on c.room_id = t.biz_id 
	where t.version <> -1 and t.view <> 1 and t.user_id = ? order by t.created_at desc`
	rows, err := m.dblink.Query(QueryStr, userId)
	if err != nil {
		log.WithField("Func", "GetTidingsList").Errorf("QueryStr:[%v] error:%v", QueryStr, err)
		return nil, err
	}
	defer rows.Close()
	TidingsList := make([]utils.TidingsVo, 0)
	for rows.Next() {
		var tidingVo utils.TidingsVo
		err = rows.Scan(&tidingVo.Id, &tidingVo.Title, &tidingVo.BizId, &tidingVo.Content, &tidingVo.View,
			&tidingVo.Theme, &tidingVo.StartTime)
		if err != nil {
			log.WithField("Func", "GetTidingsList").Errorf("scan:[%v] error:%v", QueryStr, err)
			return nil, err
		}
		TidingsList = append(TidingsList, tidingVo)
	}
	return &TidingsList, nil
}

// 修改消息阅读状态(支持批量)
func (m *MysqlImpl) UpdateView(ids string) int64 {
	defer utils.HandlePanic()
	now := utils.GetCurrentTime()
	sql := fmt.Sprintf("update mc_tidings set view = 1, updated_at = '%s' where id in (%s)", now, ids)
	res, err := m.dblink.Exec(sql)
	if err != nil {
		log.WithField("Func", "UpdateView").Errorf("sql:[%v] error: %v", sql, err)
		return -1
	}
	num, _ := res.RowsAffected()
	return num
}

// 删除消息(支持批量)
func (m *MysqlImpl) DeleteTidingsInfo(ids string) int64 {
	defer utils.HandlePanic()
	now := utils.GetCurrentTime()
	sql := fmt.Sprintf("update mc_tidings set version = -1, updated_at = '%s' where id in (%s)", now, ids)
	res, err := m.dblink.Exec(sql)
	if err != nil {
		log.WithField("Func", "DeleteTidingsInfo").Errorf("sql:[%v] error: %v", sql, err)
		return -1
	}
	num, _ := res.RowsAffected()
	return num
}

// 添加设置信息(初始化用户的默认设置信息)
func (m *MysqlImpl) AddSettings(userId int64) (bool, error) {
	defer utils.HandlePanic()
	sql := "insert into mc_setting values (?,?,?,?,?,?,?,?,?,?,?)"
	id := utils.IdGenerate()
	curTime := utils.GetCurrentTime()
	rows, err := m.dblink.Exec(sql, id, userId, 1, 1, 1, 0, 1, 1, curTime, curTime, 0)
	if err != nil {
		log.WithField("Func", "AddSettings").Errorf("sql:[%v] error: %v", sql, err)
		return false, err
	}
	var flag = true
	num, _ := rows.RowsAffected()
	if num < 1 {
		flag = false
	}
	return flag, nil
}

// 根据用户标识查询设置信息
func (m *MysqlImpl) GetPersonalSettings(userId int64) (*utils.SettingRes, error) {
	defer utils.HandlePanic()
	sql := "select id, cam_state, mic_state, com_audio, min_tray, show_speaker, show_dur " +
		"from mc_setting where userId=?"
	rows, err := m.dblink.Query(sql, userId)
	if err != nil {
		log.WithField("Func", "GetPersonalSettings").Errorf("QueryStr:[%v] error:%v", sql, err)
		return nil, err
	}
	defer rows.Close()
	var set utils.SettingRes
	if rows.Next() {
		err = rows.Scan(&set.Id, &set.Cam_state, &set.Mic_state, &set.Com_audio, &set.Min_tray,
			&set.Show_speaker, &set.Show_dur)
		if err != nil {
			log.WithField("Func", "GetPersonalSettings").Errorf("query sql:[%v] error:%v", sql, err)
			return nil, err
		}
	}
	return &set, nil
}

// 修改设置项
func (m *MysqlImpl) ModifySettings(id int64, column string, value int) (bool, error) {
	sql := "update mc_setting set " + column + "=?, updated_at=? where id=?"
	curTime := utils.GetCurrentTime()
	rows, err := m.dblink.Exec(sql, value, curTime, id)
	if err != nil {
		log.WithField("Func", "ModifySettings").Errorf("sql:[%v] error:%v", sql, err)
		return false, err
	}
	var flag = true
	num, _ := rows.RowsAffected()
	if num < 1 {
		flag = false
	}
	return flag, nil
}

// 会议历史列表查询:只查询该用户参加过的已经结束的会议
// 根据创建人、会议名称、会议号进行查询
func (m *MysqlImpl) GetHistoryConfListByParam(userId int64, queryParams string) *[]utils.HisConfeRes {
	defer utils.HandlePanic()
	var conferclosetime sql.NullString
	querySql := "SELECT CONVERT(erp.id,CHAR),eri.`id`, mc.`id`, mc.`room_id`, mc.`type`, mc.`theme`, date_format(eri.`created_at`, '%Y-%m-%d') date,DATE_FORMAT(mc.`start_time`, '%Y-%m-%d %T') startTime, DATE_FORMAT(mc.`end_time`, '%Y-%m-%d %T') endTime," +
		" mc.`cycle`, mc.`creator`, DATE_FORMAT(eri.`created_at`, '%Y-%m-%d %T') createdAt,  eri.`conf_close_time`, mc.record_flag " +
		"FROM emedia_room_info eri LEFT JOIN mc_conference mc ON mc.`room_id` = eri.`room_id` LEFT JOIN emedia_room_players erp ON eri.`id` = erp.`room_id` LEFT JOIN emedia_app_user eau ON eau.`id` = erp.`player_name` " +
		"WHERE erp.`player_name` = ? AND  mc.`version` != -1 And erp.`version` !=-1  order by erp.`exit_time` desc"

	rows, err := m.dblink.Query(querySql, userId)
	if err != nil {
		log.WithField("Func", "GetHistoryConfListByParam").Warnf("querySql:[%v] err: %v", querySql, err)
		return nil
	}
	defer rows.Close()
	confeHisListReq := make([]utils.HisConfeRes, 0)
	startTime := ""
	for rows.Next() {
		var hisConfer utils.HisConferenceRes
		err = rows.Scan(&hisConfer.RoomPlayerId, &hisConfer.RoomPriKey, &hisConfer.Id, &hisConfer.RoomId, &hisConfer.Type, &hisConfer.Theme, &startTime, &hisConfer.StartTime,
			&hisConfer.EndTime, &hisConfer.Cycle, &hisConfer.CreatorId, &hisConfer.ConfCreateTime, &conferclosetime, &hisConfer.RecordFlag)
		if err != nil {
			log.WithField("Func", "GetHistoryConfListByParam").Warnf("Scan:%v", err)
			continue
		}

		//根据返回的创建人id进行查询对应的昵称和头像
		queryCreatorSql := " SELECT eau.`nickname`,eau.`avatar` FROM emedia_app_user eau WHERE id = ?"
		rowsCreateor, errCreator := m.dblink.Query(queryCreatorSql, hisConfer.CreatorId)
		if errCreator != nil {
			log.WithField("Func", "GetHistoryConfListByParam").Warnf("queryCreatorSql:[%v] err: %v", queryCreatorSql, errCreator)
			continue
		}
		defer rowsCreateor.Close()
		if rowsCreateor.Next() {
			errCreator := rowsCreateor.Scan(&hisConfer.Creator, &hisConfer.CreatorAvator)
			if errCreator != nil {
				log.WithField("Func", "GetHistoryConfListByParam").Warnf("scan:[%v] err:%v", "select creator info", errCreator)
				continue
			}
		}
		//根据查询结果进行匹配查找 发起人；会议主题；会议id
		if queryParams != "" {
			if queryParams != *hisConfer.Creator && queryParams != hisConfer.Theme && queryParams != hisConfer.Id {
				continue
			}
		}
		hisClr := utils.HisConfeRes{
			StartTime:    startTime,
			HisConfeList: make([]utils.HisConferenceRes, 0),
		}
		//时间戳转成时间字符串处理
		if conferclosetime.String != "" {
			j, _ := strconv.ParseInt(hisConfer.ConfCloseTime, 10, 64)
			formatconfCloseStr := time.UnixMilli(j).Format("2006-01-02 15:04:05")
			hisConfer.ConfCloseTime = formatconfCloseStr
		} else {
			hisConfer.ConfCloseTime = time.Now().Format("2006-01-02 15:04:05")
		}

		hisClr.HisConfeList = append(hisClr.HisConfeList, hisConfer)
		confeHisListReq = append(confeHisListReq, hisClr)
	}
	return &confeHisListReq
}

// 根据主键获取历史会议详情信息
func (m *MysqlImpl) GetHisConferDetailById(confeId int64) *utils.HisConfeDetailRes {
	defer utils.HandlePanic()
	var confDetail utils.HisConfeDetailRes
	QueryRecordStr := "SELECT eri.`record` FROM mc_conference mc LEFT JOIN emedia_room_info eri ON eri.`room_id` = mc.`room_id` WHERE eri.`id` = ?"
	rows, err := m.dblink.Query(QueryRecordStr, confeId)
	if err != nil {
		log.WithField("Func", "GetHisConferDetailById").Warnf("Query:[%v] err:%v", QueryRecordStr, err)
		return nil
	}
	defer rows.Close()
	var record sql.NullString

	if rows.Next() {
		err = rows.Scan(&record)
		if err != nil {
			log.WithField("Func", "GetHisConferDetailById").Warnf("scan:[%v] err:%v", QueryRecordStr, err)
			return nil
		}

		videoUrls := make([]utils.VideoUrls, 0)
		if record.String != "" {
			split := strings.Split(record.String, "#")
			for _, value := range split {
				vul := utils.VideoUrls{}
				valutSplit := strings.Split(value, "/")
				lastStr := valutSplit[len(valutSplit)-1]
				vul.RecordId = lastStr
				vul.VideoUrl = value
				videoUrls = append(videoUrls, vul)
			}
		}
		confDetail.Records = videoUrls

	}
	// 2.根据会议id获取对应的参会人员的头像url
	QueryAvatorsStr := "SELECT eau.`avatar` FROM emedia_app_user eau WHERE eau.`id` IN " +
		"(SELECT erp.`player_name` FROM emedia_room_players erp LEFT JOIN emedia_room_info eri ON erp.`room_id` = eri.`id` LEFT JOIN mc_conference mc ON mc.`room_id` = eri.`room_id` WHERE eri.`id` = ?)"

	rowsAvator, errAvator := m.dblink.Query(QueryAvatorsStr, confeId)
	if errAvator != nil {
		log.WithField("Func", "GetHisConferDetailById").Warnf("Query:[%v] err:%v", QueryAvatorsStr, errAvator)
		return nil
	}
	defer rowsAvator.Close()
	var userAvatror utils.UserAvators
	userAvatorMake := make([]utils.UserAvators, 0)
	for rowsAvator.Next() {
		errAvator = rowsAvator.Scan(&userAvatror.AvatorUrl)
		if errAvator != nil {
			log.WithField("Func", "GetHisConferDetailById").Warnf("scan:[%v] err:%v", QueryAvatorsStr, errAvator)
			return nil
		}
		userAvatorMake = append(userAvatorMake, userAvatror)
	}
	confDetail.UserAvators = userAvatorMake
	return &confDetail
}

// 删除会议视频记录
func (m *MysqlImpl) DeleteConferenceRecord(id int64, userId string, recordId string) bool {
	defer utils.HandlePanic()
	//查询获取会议信息：emedia_room_info
	querySql := "SELECT eri.id,mc.`creator`,eri.record FROM emedia_room_info eri LEFT JOIN mc_conference mc ON eri.`room_id` = mc.`room_id` WHERE eri.`id` = ?"
	rowsQuery, errQuery := m.dblink.Query(querySql, id)
	if errQuery != nil {
		log.WithField("Func", "DeleteConferenceRecord").Warnf("querySql:[%v] error: %v", querySql, errQuery)
		return false
	}
	defer rowsQuery.Close()
	roomId := ""
	recordUrlNew := ""
	if rowsQuery.Next() {
		createrId := ""
		recordUrl := ""
		err := rowsQuery.Scan(&roomId, &createrId, &recordUrl)
		if err != nil {
			log.WithField("Func", "DeleteConferenceRecord").Warnf("rowsQuery error: %v", err)
			return false
		}
		if createrId != userId {
			//不是会议发起人不允许删除会议视频记录
			log.WithField("Func", "DeleteConferenceRecord").Warnf("verify delete record not pass createrId: %v", createrId)
			return false
		}
		//处理可能是多个录制的情况
		split := strings.Split(recordUrl, "#")
		values := make([]string, 0)
		for _, value := range split {
			valutSplit := strings.Split(value, "/")

			lastStr := valutSplit[len(valutSplit)-1]
			if lastStr == recordId {
				continue
			}
			values = append(values, value)
		}
		//如果values的长度是大于2条，按照原来格式进行重新拼接下
		valuesLen := len(values)
		if valuesLen == 1 {
			recordUrlNew = values[0]
		} else if valuesLen > 1 {
			for index, v := range values {
				if index == valuesLen-1 {
					//最后一条数据
					recordUrlNew += v
				} else {
					recordUrlNew += v + "#"
				}
			}
		}

	}
	//修改url为空
	updateSql := "update emedia_room_info set record = ? where id = ?"
	ret, errUpdate := m.dblink.Exec(updateSql, recordUrlNew, roomId)
	if errUpdate != nil {
		log.WithField("Func", "DeleteConferenceRecord").Warnf("updateSql:[%v] error: %v", updateSql, errUpdate)
		return false
	}
	var flag = true
	num, _ := ret.RowsAffected()
	if num < 1 {
		flag = false
	}
	return flag
}

func (m *MysqlImpl) GetRoomInfoByAppIdAndRoomId(appid int64, roomId string) (error, utils.EmediaRoomInfo) {
	defer utils.HandlePanic()
	roomInfo := utils.EmediaRoomInfo{}
	var record sql.NullString
	sql := "select id, app_id, room_id,conf_id, password, record from emedia_room_info where app_Id=? and room_id=? order by confr_create_time desc limit 1"
	rowsQuery, errQuery := m.dblink.Query(sql, appid, roomId)
	if errQuery != nil {
		log.WithField("Func", "GetRoomInfoByAppIdAndRoomId").Warnf("querySql:[%v] error: %v", sql, errQuery)
		return errQuery, roomInfo
	}
	defer rowsQuery.Close()
	if rowsQuery.Next() {
		err := rowsQuery.Scan(&roomInfo.Id, &roomInfo.AppId, &roomInfo.RoomId, &roomInfo.ConfrId, &roomInfo.Password, &record)
		if err != nil {
			log.WithField("Func", "GetRoomInfoByAppIdAndRoomId").Warnf("rowsQuery error: %v", err)
			return err, roomInfo
		}
		roomInfo.Record = record.String
		log.WithField("Func", "GetRoomInfoByAppIdAndRoomId").Warnf("rowsQuery id is: %d", roomInfo.Id)
		return nil, roomInfo
	}
	return errors.New("No data"), roomInfo
}

func (m *MysqlImpl) GetRoomInfoByAppIdAndMeetId(appid int64, meetId string) (error, utils.EmediaRoomInfo) {
	defer utils.HandlePanic()
	roomInfo := utils.EmediaRoomInfo{}
	var record sql.NullString
	sql := "select id, app_id, room_id,conf_id, password, record from emedia_room_info where app_Id=? and uuid=?"
	rowsQuery, errQuery := m.dblink.Query(sql, appid, meetId)
	if errQuery != nil {
		log.WithField("Func", "GetRoomInfoByAppIdAndMeetId").Warnf("querySql:[%v] error: %v", sql, errQuery)
		return errQuery, roomInfo
	}
	defer rowsQuery.Close()
	if rowsQuery.Next() {
		err := rowsQuery.Scan(&roomInfo.Id, &roomInfo.AppId, &roomInfo.RoomId, &roomInfo.ConfrId, &roomInfo.Password, &record)
		if err != nil {
			log.WithField("Func", "GetRoomInfoByAppIdAndMeetId").Warnf("rowsQuery error: %v", err)
			return err, roomInfo
		}
		roomInfo.Record = record.String
		log.WithField("Func", "GetRoomInfoByAppIdAndMeetId").Warnf("rowsQuery id is: %d", roomInfo.Id)
		return nil, roomInfo
	}
	return errors.New("No data"), roomInfo
}

func (m *MysqlImpl) GetRoomInfoById(roomInfoId int64) utils.EmediaRoomInfo {
	defer utils.HandlePanic()
	roomInfo := utils.EmediaRoomInfo{}
	var record sql.NullString
	sql := "select id, room_id, record, state from emedia_room_info where id=?"
	rows, err := m.dblink.Query(sql, roomInfoId)
	if err != nil {
		log.WithField("Func", "GetRoomInfoById").Errorf("querySql:[%v] error: %v", sql, err)
		return roomInfo
	}
	defer rows.Close()
	if rows.Next() {
		err := rows.Scan(&roomInfo.Id, &roomInfo.RoomId, &record, &roomInfo.State)
		if err != nil {
			log.WithField("Func", "GetRoomInfoById").Errorf("rowsQuery error: %v", err)
			return roomInfo
		}
		roomInfo.Record = record.String
	}
	return roomInfo
}

func (m *MysqlImpl) InsertRtcEvent(roomInfo *utils.EmediaRoomInfo, request *utils.EvtDataReq) {
	defer utils.HandlePanic()
	id := utils.IdGenerate()
	detail, _ := json.Marshal(*request)
	currentTime := utils.GetCurrentTime()
	sql := "insert into vedio_rtc_event_log values(?,?,?,?,?,?,?,?,?)"
	m.dblink.Exec(sql, id, roomInfo.AppId, roomInfo.Id, request.ConferId, request.EvtType, string(detail), currentTime, currentTime, 0)
}
func (m *MysqlImpl) UpdateRoomInfoStatus(Id int64, ordinal int, timestamp int64, confrId string) {
	defer utils.HandlePanic()
	sql := "update emedia_room_info set state=?,conf_id=? where id=?"
	m.dblink.Exec(sql, ordinal, confrId, Id)
}
func (m *MysqlImpl) InsertRoomPlayUser(roomInfo *utils.EmediaRoomInfo, request *utils.EvtDataReq, timestamp int64) {
	defer utils.HandlePanic()
	id := utils.IdGenerate()
	currentTime := utils.GetCurrentTime()
	sql := "insert into emedia_room_players set id=?,app_id=?,room_id=?,player_name=?,conf_id=?,password=?,enter_time=?,created_at=?,updated_at=?,version=?"
	_, err := m.dblink.Exec(sql, id, roomInfo.AppId, roomInfo.Id, request.MemName, roomInfo.ConfrId, roomInfo.Password,
		timestamp, currentTime, currentTime, 0)
	if err != nil {
		log.WithField("Func", "InsertRoomPlayUser").Errorf("insert the room players err %v", err)

	}
}

func (m *MysqlImpl) UpdateUserExitRoomPlayTime(Id int64, memName string, timestamp int64) {
	defer utils.HandlePanic()
	sql := "update emedia_room_players set exit_time=? where room_id=? and player_name=? order by enter_time desc limit 1"
	_, err := m.dblink.Exec(sql, timestamp, Id, memName)
	if err != nil {
		log.WithField("Func", "UpdateUserExitRoomPlayTime").Errorf("update the room players exit time err %v,%d,%s", err, Id, memName)

	}
}
func (m *MysqlImpl) CloseRoom(Id int64, ordinal int, timestamp int64) {
	defer utils.HandlePanic()
	sql := "update emedia_room_info set state=?, conf_close_time=? where id=?"
	_, err := m.dblink.Exec(sql, ordinal, timestamp, Id)
	log.WithField("Func", "CloseRoom").Errorf("update emedia_room_info err %v,%d,%d", err, Id, ordinal)

	if err != nil {
		log.WithField("Func", "CloseRoom").Errorf("update emedia_room_info err %v,%d,%d", err, Id, ordinal)
	}
}

func (m *MysqlImpl) UpdateRecord(Id int64, PlayURL string, userName string, record string) {
	defer utils.HandlePanic()
	url := PlayURL
	if record != "" {
		url = record + "#" + PlayURL
	}
	currentTime := utils.GetCurrentTime()

	log.WithField("Func", "UpdateRecord").Errorf("update record the url is:%s,%d,%s", url, Id, userName)

	if userName != "" {
		sql := "update emedia_room_players set record=?, updated_at=? where room_id=? and player_name=?"
		_, err := m.dblink.Exec(sql, url, currentTime, Id, userName)
		if err != nil {
			log.WithField("Func", "UpdateRecord").Errorf("update record sql is:%s,%v", sql, err)
		}
	} else {
		sql := "update emedia_room_info set record=?, updated_at=? where id=?"
		_, err := m.dblink.Exec(sql, url, currentTime, Id)
		if err != nil {
			log.WithField("Func", "UpdateRecord").Errorf("update record sql is:%s,%v", sql, err)
		}
	}
}

func (m *MysqlImpl) UpdateConferRecordFlag(room_id string) bool {
	defer utils.HandlePanic()
	editSql := "UPDATE mc_conference SET record_flag = record_flag + 1 WHERE room_id = ?"
	ret, err := m.dblink.Exec(editSql, room_id)
	if err != nil {
		log.WithField("Func", "EditConfeRecordFlag").Warnf(" editSql:[%v], error:%v", editSql, err)
		return false
	}
	flag := true
	num, err := ret.RowsAffected()
	log.WithField("Func", "mysql EditConfeRecordFlag").Infof(" editSql:[%v],%v, error:%v the rowsnum is:%d", editSql, room_id, err, num)

	return flag
}

// 修改会议录制记录标识
func (m *MysqlImpl) EditConfeRecordFlag(id int64, recordFlag int) bool {
	defer utils.HandlePanic()
	//不清楚原来的逻辑updateAt是否有其他用， 这个字段更改暂时不修改事件
	//updateTime := utils.GetCurrentTime()
	editSql := "UPDATE mc_conference SET record_flag = ? WHERE id = ?"
	ret, err := m.dblink.Exec(editSql, recordFlag, id)
	if err != nil {
		log.WithField("Func", "EditConfeRecordFlag").Warnf(" editSql:[%v], error:%v", editSql, err)
		return false
	}
	flag := true
	num, err := ret.RowsAffected()
	log.WithField("Func", "mysql EditConfeRecordFlag").Infof(" editSql:[%v], error:%v the rowsnum is:%d", editSql, err, num)
	//num, err := ret.RowsAffected()
	//if num < 1 || err != nil {
	//	log.WithField("Func", "mysql EditConfeRecordFlag").Warnf(" editSql:[%v], error:%v the rowsnum is:%d", editSql, err, num)
	//	flag = false
	//}
	return flag
}
func (m *MysqlImpl) AddWhiteboardRecord(num, meeting_duration int, startTime int64, meetingpath, RoomId, UserId, UploadPath string) {
	defer utils.HandlePanic()
	sql := "insert into recordfilehistory set start_time=?,room_id=?,user_id=?,num=?,upload_path=?,meeting_path =?,meeting_duration=?"
	_, err := m.dblink.Exec(sql, startTime, RoomId, UserId, num, UploadPath, meetingpath, meeting_duration)
	if err != nil {
		log.WithField("Func", "InsertRoomPlayUser").Errorf("AddWhiteboardRecord %v", err)
	}
}

func (m *MysqlImpl) UpdateWhiteboardRecord(meetingpath, UploadPath string) {
	defer utils.HandlePanic()
	sql := "UPDATE recordfilehistory SET meeting_path = ? WHERE upload_path = ?"
	m.dblink.Exec(sql, meetingpath, UploadPath)
}

func (m *MysqlImpl) UpdateWhiteboardDuration(duration int, uploadpath string) {
	defer utils.HandlePanic()
	sql := "UPDATE recordfilehistory SET duration = ? WHERE upload_path = ?"
	m.dblink.Exec(sql, duration, uploadpath)
}
